﻿using FinalPointSet.Model.Asset;
using FinalPointSet.Model.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace FinalPointSet.Model.Model.MockData
{
    public class MockFormatter
    {
        /// <summary>
        /// 获取插入数据的SQL语句
        /// </summary>
        /// <param name="mockResult">模拟数据</param>
        /// <param name="path">保存的路径</param>
        /// <param name="tableName">表名</param>
        /// <returns></returns>
        public static void ExportSQL(MockResult mockResult, string path, string tableName)
        {
            //插入语句的模板
            string strInsert = $"INSERT INTO {tableName} ($fields) VALUES\n"
            + "$datas;";

            //表头
            StringBuilder sbHead = new();
            for (int i = 0; i < mockResult.Header.Count; i++)
            {

                if (i == mockResult.Header.Count - 1)
                {
                    sbHead.Append($"`{mockResult.Header[i]}`");
                }
                else
                {
                    sbHead.Append($"`{mockResult.Header[i]}`,");
                }
            }
            string strHeader = sbHead.ToString();

            StringBuilder sbDatas = new();
            List<List<string>> mockDatas = mockResult.FieldDatas;
            //拼接数据
            for (int n = 0; n < mockDatas.Count; n++)
            {
                StringBuilder sbLine = new();
                for (int i = 0; i < mockDatas[0].Count; i++)
                {
                    if (mockDatas[0].Count == 1)
                    {
                        sbLine.Append($"('{mockDatas[n][i]}')");
                    }
                    else
                    {
                        if (i == 0)
                        {
                            sbLine.Append($"('{mockDatas[n][i]}',");
                        }
                        else if (i == mockDatas[0].Count - 1)
                        {
                            sbLine.Append($"'{mockDatas[n][i]}')");
                        }
                        else
                        {
                            sbLine.Append($"'{mockDatas[n][i]}',");
                        }
                    }
                }
                if (n == 0)
                {
                    if (mockDatas.Count > 1)
                    {
                        sbDatas.AppendLine(" " + sbLine.ToString());
                    }
                    else
                    {
                        sbDatas.AppendLine(sbLine.ToString());
                    }
                }
                else
                {
                    sbDatas.AppendLine("," + sbLine.ToString());
                }
            }

            //替换模板的关键词,返回最终的结果
            string sql = strInsert.Replace("$fields", strHeader).Replace("$datas", sbDatas.ToString());
            string curTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string exportFileName = $"MockData_{curTime}.sql";
            string exportFilePath = $"{path}\\{exportFileName}";
            // 如果输出目录不存在，则创建它  
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            Debug.Print(exportFilePath);
            AssetUtil.SaveTextAsFile(sql, exportFilePath);
        }

        /// <summary>
        /// 导出数据为文件
        /// </summary>
        /// <param name="mockResult">模拟数据</param>
        /// <param name="path">导出路径</param>
        /// <param name="type">导出类型</param>
        /// <param name="hasHeader">是否导出表头</param>
        public static void ExportFile(MockResult mockResult, string path, ExportFileType type, bool hasHeader = true)
        {
            string curTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string exportFileName = $"MockData_{curTime}.{type.ToString().ToLower()}";
            string exportFilePath = $"{path}\\{exportFileName}";
            // 如果输出目录不存在，则创建它  
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            Debug.Print(exportFilePath);

            //开始写入数据到文件
            using var writer = new StreamWriter(exportFilePath);
            List<List<string>> datas = mockResult.FieldDatas;
            if (hasHeader)
            {
                string[] header = mockResult.Header.ToArray();
                // 写入标题行
                WriteLine(writer, header);
            }
            // 写入数据行
            for (int i = 0; i < datas.Count; i++)
            {
                string[] values = [.. datas[i]];
                if (i == datas.Count - 1)
                {
                    Write(writer, values);
                }
                else
                {
                    WriteLine(writer, values);
                }
            }
            writer.Close();
        }
        private static void WriteLine(StreamWriter writer, string[] values)
        {
            string line = string.Join(",", values);
            writer.WriteLine(line);
        }
        private static void Write(StreamWriter writer, string[] values)
        {
            string line = string.Join(",", values);
            writer.Write(line);
        }
    }
}
